#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../../lv_demos/lv_demo.h"
#include "ft_main.h"

//static lv_obj_t *scr_main=NULL;
static lv_obj_t *win_main = NULL;
static lv_obj_t * btnm1 = NULL;

static const char * btnm_map[] = { "Audio Test","\n",
	"\n",
 "Spk Test", "\n",
 "Loop Test",  "\n",
 "fail", "pass",
 "" };


static void ft_audio_destory(void)
{
	printf("ft_audio_destory + \n");
	if (win_main != NULL) {
		lv_obj_del(win_main);
		win_main = NULL;
		btnm1 = NULL;
	}

}

static void spk_play_pcm_test(lv_timer_t *tmr)
{
	(void)tmr;
	printf("spk_play_pcm_test \n");
	if (btnm1 != NULL) { 
		lv_btnmatrix_clear_btn_ctrl(btnm1, 1, LV_BTNMATRIX_CTRL_DISABLED); 
	}

}
static void spk_mic_loop_test(lv_timer_t *tmr)
{
	(void)tmr;
	printf("spk_mic_loop_test \n");
	if (btnm1 != NULL) {
		lv_btnmatrix_clear_btn_ctrl(btnm1, 2, LV_BTNMATRIX_CTRL_DISABLED);
	}
}


static void event_handler(lv_event_t *event)
{
	uint32_t data = 0;
	data = (uint32_t)lv_event_get_user_data(event);
	lv_obj_t * obj = lv_event_get_target(event);
	uint16_t index = lv_btnmatrix_get_selected_btn(obj);
	printf("[Ft_key]Clicked: index=%d\n", index);
	if (event->code == LV_EVENT_VALUE_CHANGED) {
		printf("[Ft_key]Clicked: data=%ld\n", data);

		switch (data)
		{

		case 0xa1:
		{
			if (index ==1) {
				lv_btnmatrix_set_btn_ctrl(btnm1, 1, LV_BTNMATRIX_CTRL_DISABLED);
				lv_timer_t *task = lv_timer_create(spk_play_pcm_test, 1000, NULL);
				lv_timer_set_repeat_count(task,1);
			
			}
			else if (index == 2) {
				lv_btnmatrix_set_btn_ctrl(btnm1, 2, LV_BTNMATRIX_CTRL_DISABLED);
				lv_timer_t *task1 = lv_timer_create(spk_mic_loop_test, 1000, NULL);
				lv_timer_set_repeat_count(task1, 1);

			}
			else if (index == 3) {
				lv_btnmatrix_set_btn_ctrl(btnm1, index, LV_BTNMATRIX_CTRL_CHECKED);
			
				g_item_result[4] = 0;
				ft_main_refresh_list((void*)0x04);
				ft_audio_destory();
				
			}
			else if (index == 4) {
				lv_btnmatrix_set_btn_ctrl(btnm1, index, LV_BTNMATRIX_CTRL_CHECKED);
				g_item_result[4] = 1;
				ft_main_refresh_list((void*)0x04);
				ft_audio_destory();
				
			}

		}
		break;
		default:
			break;
		}
	}
}


static void ft_audio_init_view(void)
{
	printf("ft_audio_init_view + \n");
	//scr_main = lv_obj_create(NULL);
	//lv_scr_load(scr_main);
	win_main = lv_win_create(lv_scr_act(), 0);
	lv_obj_set_size(win_main, 240, 320);


	btnm1 = lv_btnmatrix_create(win_main);
	lv_obj_set_size(btnm1, 240, 320);
	lv_btnmatrix_set_map(btnm1, btnm_map);

	lv_btnmatrix_set_btn_ctrl(btnm1, 0, LV_BTNMATRIX_CTRL_DISABLED);
	lv_btnmatrix_set_btn_ctrl(btnm1, 0, LV_BTNMATRIX_CTRL_CHECKED);
	lv_obj_align(btnm1, LV_ALIGN_CENTER, 0, 0);
	lv_obj_add_event_cb(btnm1, event_handler, LV_EVENT_VALUE_CHANGED, (void *)0xa1);

}


void ft_audio_create(void)
{
	printf("ft_audio_create + \n");
	ft_audio_init_view();

}